package com.gae.blore.server.dao;

import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;

public abstract class AbstractDao<T> {

	public void saveOrUpdate(T t) {

		System.out.println("Start creat");
		PersistenceManager pm = getPersistenceManager();
		try {
			pm.makePersistent(t);
		} catch (Exception exception) {
			exception.printStackTrace();
		} finally {
			pm.close();
		}
		System.out.println("End creat");

	}

	public void saveAll(Collection<T> collection) {

		System.out.println("Start creat");
		PersistenceManager pm = getPersistenceManager();
		try {
			pm.makePersistentAll(collection);
		} catch (Exception exception) {
			exception.printStackTrace();
		} finally {
			pm.close();
		}
		System.out.println("End creat");

	}

	public void delete(Long id) {

		System.out.println("Start creat");
		PersistenceManager pm = getPersistenceManager();
		try {

			Object networkElement = pm.getObjectById(getReferenceClass(), id);
			pm.deletePersistent(networkElement);
		} catch (Exception exception) {
			exception.printStackTrace();
		} finally {
			pm.close();
		}
		System.out.println("End creat");

	}

	public List<T> findAll() {
		PersistenceManager pm = getPersistenceManager();

		Collection<T> detachedelements;
		String query = "select from " + getReferenceClass().getName();
		try {

			detachedelements = pm.detachCopyAll((List<T>) pm.newQuery(query)
					.execute());
		} finally {
			pm.close();
		}

		return (List<T>) detachedelements;

	}

	public T findById(Long id) {
		PersistenceManager pm = getPersistenceManager();
		T t = null;
		try {
			t = (T) pm.getObjectById(getReferenceClass(), id);
		} finally {
			pm.close();
		}
		return t;
	}

	public List<T> findByQuery(String query) {
		PersistenceManager pm = getPersistenceManager();

		Collection<T> detachedelements;
		try {

			detachedelements = pm.detachCopyAll((List<T>) pm.newQuery(query)
					.execute());
		} finally {
			pm.close();
		}

		return (List<T>) detachedelements;

	}

	public abstract Class getReferenceClass();

	public PersistenceManager getPersistenceManager() {
		return PMF.get().getPersistenceManager();
	}

}
